<!--
@license
Copyright (c) 2016 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->
<link rel="import" href="../bower_components/plugin-element/plugin-element.html">
<dom-module id="shop-category-data">
    <script>
        
        (function() {
            var catehories = null;
            var products = null;
            class ShopCategoryData extends PluginElement {

                static get is() {
                    return 'shop-category-data';
                }

                static get properties() {
                    return {

                        categoryName: {
                            type:String,
                            observer:"_categoryInit"
                        },

                        itemName: String,

                        categories: {
                            type: Array,
                            value:function(){
                                if(!catehories){
                                    catehories = new Array();
                                   let xhr = new XMLHttpRequest();
                                    xhr.withCredentials = true;
                                    xhr.addEventListener('load',function(e){
                                        let cats = JSON.parse(e.target.responseText).result;
                                        for(let i=0;i<cats.length;i++){
                                            let cat = cats[i];
                                            catehories.push({name:String(cat.id),title:cat.name,image:cat.pic,placeholder:""});
                                        }
                                    });
                                    xhr.open('GET',app.apiHost+"/product.category.list.nothide?app_id="+app.appId,false);
                                    xhr.send();
                                }
                                
                                return catehories;
                            },
                            readOnly: true,
                            notify: true
                        },

                        category: {
                            type: Object,
                            notify: true
                        },

                        item: {
                            type: Object,
                            computed: '_computeItem(category.items, itemName)',
                            notify: true
                        },

                        failure: {
                            type: Boolean,
                            notify: true,
                            readOnly: true
                        }

                    }
                }
                ready(){
                    super.ready();
                    let dom = this;
                    if(!products){
                        products = new Array();
                        let xhr = new XMLHttpRequest();
                        xhr.withCredentials = true;
                        xhr.addEventListener("load",function(e){
                            let items = JSON.parse(e.target.responseText).result;
                            for(let i=0;i<items.length;i++){
                                let item = items[i];
                                items[i]={name:String(item.id),title:item.name,category:String(item.category_id),price:item.salemoney,market_price:item.market_price,description:item.name,image:dom._albumItem(item.album,0,300,300),largeImage:dom._albumItem(item.album,0,750,750),defauleImage:item.album[0],amount:item.amount};
                            }
                            products = items;
                        });
                        xhr.open('GET', app.apiHost+"/product.list?app_id="+app.appId,false);
                        xhr.send();
                    }
                }
                _getCategoryObject(categoryName) {
                    for (let i = 0, c; c = this.categories[i]; ++i) {
                        if (c.name === categoryName) {
                            return c;
                        }
                    }
                }
                _categoryInit(cname){
                    if(cname){
                        this.category = this._getCategoryObject(cname);
                        this._fetchItems(this.category, 1);
                    }
                }
                getItem(name){
                    for(let i=0;i<products.length;i++){
                        let pro = products[i];
                        if(String(name)==String(pro.name)){
                           return pro;
                        }
                    }
                }

                _computeItem(items, itemName) {
                    if (!items || !itemName) {
                        return;
                    }
                    for (let i = 0, item; item = items[i]; ++i) {
                        if (item.name === itemName) {
                            return item;
                        }
                    }
                }

                _fetchItems(category, attempts) {
                    let dom = this;
                    this._setFailure(false);
                    // Only fetch the items of a category if it has not been previously set.
                    if (!category || category.items) {
                        return;
                    }
                    let items = [];
                    for(let i=0;i<products.length;i++){
                        if(products[i].category==category.name){
                           items.push(products[i]);
                        }
                    }
                    this.set('category.items',items);
                }

                _getResource(rq, attempts) {
                    let xhr = new XMLHttpRequest();
                    xhr.withCredentials = true;
                    xhr.addEventListener('load', rq.onLoad.bind(this));
                    xhr.addEventListener('error', (e) => {
                        // Flaky connections might fail fetching resources
                        if (attempts > 1) {
                            this._getResourceDebouncer = Polymer.Debouncer.debounce(this._getResourceDebouncer,
                                Polymer.Async.timeOut.after(200), this._getResource.bind(this, rq, attempts - 1));
                        } else {
                            rq.onError.call(this, e);
                        }
                    });

                    xhr.open('GET', rq.url);
                    xhr.send();
                }

                refresh() {
                    
                    if (this.categoryName) {
                        // Try at most 3 times to get the items.
                        this._fetchItems(this._getCategoryObject(this.categoryName), 3);
                    }
                }
            }

            customElements.define(ShopCategoryData.is, ShopCategoryData);

        })();

    </script>
    
</dom-module>
